package com.sunchangming.stmdb;

public class Decoder {
	static public void writeRawVarint32(java.io.DataOutputStream dis, int value) throws java.io.IOException {
		while (true) {
			if ((value & ~0x7F) == 0) {
				dis.writeByte(value);
				return;
			} else {
				dis.writeByte((value & 0x7F) | 0x80);
				value >>>= 7;
			}
		}
	}

	static public int readRawVarint32(java.io.DataInputStream dis) throws java.io.IOException {
		byte tmp = dis.readByte();
		if (tmp >= 0) {
			return tmp;
		}
		int result = tmp & 0x7f;
		if ((tmp = dis.readByte()) >= 0) {
			result |= tmp << 7;
		} else {
			result |= (tmp & 0x7f) << 7;
			if ((tmp = dis.readByte()) >= 0) {
				result |= tmp << 14;
			} else {
				result |= (tmp & 0x7f) << 14;
				if ((tmp = dis.readByte()) >= 0) {
					result |= tmp << 21;
				} else {
					result |= (tmp & 0x7f) << 21;
					result |= (tmp = dis.readByte()) << 28;
					if (tmp < 0) {
						// Discard upper 32 bits.
						for (int i = 0; i < 5; i++) {
							if (dis.readByte() >= 0) {
								return result;
							}
						}
						throw new RuntimeException("wrong data");
					}
				}
			}
		}
		return result;
	}
}
